{{- define "main_scrape_interval" }}
    {{- $context := . }}
{{- $context.Values.prometheus.scrapeInterval | default "30s" }}
{{- end }}

{{- define "authorization_config" }}
  {{- $context := index . 0 }}
  {{- $interval := index . 1 }}
jsonData:
  httpMethod: POST
  timeInterval: {{ $interval }}
  httpHeaderName1: 'Authorization'
  tlsSkipVerify: true
secureJsonData:
  httpHeaderValue1: 'Bearer $PROMETHEUS_TOKEN'
{{- end }}

{{- define "render_grafana_datasources_config" }}
apiVersion: 1

deleteDatasources:
- name: trickster
  orgId: 1
- name: trickster-longterm
  orgId: 1

  {{- if eq (int .Values.prometheus.longtermRetentionDays) 0 }}
- name: longterm
  orgId: 1
  {{- end }}

  {{- if (include "helm_lib_ha_enabled" .) }}
- name: main-0
  orgId: 1
- name: main-1
  orgId: 1
  {{- end }}

datasources:
- name: main-old
  type: prometheus
  access: proxy
  orgId: 1
  url: https://trickster.d8-monitoring.svc.{{ .Values.global.discovery.clusterDomain }}/trickster/main
  version: 1
  {{- include "authorization_config" (list . (include "main_scrape_interval" . )) | nindent 2 }}

- name: main
  type: prometheus
  access: proxy
  orgId: 1
  url: https://aggregating-proxy.d8-monitoring.svc.{{ .Values.global.discovery.clusterDomain }}
  version: 1
  isDefault: true
  {{- include "authorization_config" (list . (include "main_scrape_interval" . )) | nindent 2 }}

  {{- if ne (int .Values.prometheus.longtermRetentionDays) 0 }}
- name: longterm
  type: prometheus
  access: proxy
  orgId: 1
  url: https://trickster.d8-monitoring.svc.{{ .Values.global.discovery.clusterDomain }}/trickster/longterm
  version: 1
  {{- include "authorization_config" (list . "5m") | nindent 2 }}
  {{- end }}

  {{- if (include "helm_lib_ha_enabled" .) }}
- name: main-uncached-0
  type: prometheus
  access: proxy
  orgId: 1
  url: https://prometheus-main-0.d8-monitoring.svc.{{ .Values.global.discovery.clusterDomain }}:9090
  version: 1
  {{- include "authorization_config" (list . (include "main_scrape_interval" . )) | nindent 2 }}

- name: main-uncached-1
  type: prometheus
  access: proxy
  orgId: 1
  url: https://prometheus-main-1.d8-monitoring.svc.{{ .Values.global.discovery.clusterDomain }}:9090
  version: 1
  {{- include "authorization_config" (list . (include "main_scrape_interval" . )) | nindent 2 }}
  {{- end }}

{{- end }}

{{- define "render_grafana_additional_datasources_config" }}
apiVersion: 1

datasources:
  {{- .Values.prometheus.internal.grafana.additionalDatasources | toYaml | nindent 2 }}
{{- end }}

---
apiVersion: v1
kind: Secret
metadata:
  name: grafana-datasources
  namespace: d8-monitoring
  {{- include "helm_lib_module_labels" (list . (dict "app" "grafana")) | nindent 2 }}
data:
  prometheus.yaml: {{ include "render_grafana_datasources_config" . | b64enc | quote }}
{{ if .Values.prometheus.internal.grafana.additionalDatasources }}
  additional_datasources.yaml: {{ include "render_grafana_additional_datasources_config" . | b64enc | quote }}
{{- end }}
